package com.zzb.learning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzb.content.model.po.CoursePublish;
import com.zzb.learning.feignclient.ContentServiceClient;
import com.zzb.learning.mapper.XcChooseCourseMapper;
import com.zzb.learning.model.dto.XcChooseCourseDto;
import com.zzb.learning.model.dto.XcCourseTablesDto;
import com.zzb.learning.model.po.XcChooseCourse;
import com.zzb.learning.model.po.XcCourseTables;
import com.zzb.learning.service.CourseTablesService;
import com.zzb.learning.service.XcChooseCourseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * @Author zzb
 * @Date 2024/7/11 11:14
 * @Version 1.0
 * @description
 */
@Service
@Slf4j
public class XcChooseCourseServiceImpl extends ServiceImpl<XcChooseCourseMapper, XcChooseCourse> implements XcChooseCourseService {
    @Autowired
    private ContentServiceClient contentServiceClient;
    @Autowired
    private CourseTablesService courseTablesService;

    /**
     * 收费课程，创建订单，待用户支付完订单后，支付成功则添加到课程表中，
     * 通过延迟队列，若为支付，则取消订单，删除选课记录表中的选课记录
     * @param courseId
     * @param userId
     * @return
     */
    @Override
    @Transactional
    public XcChooseCourseDto addChooseCourse(Long courseId, String userId) {
        //根据courseId查询课程
        CoursePublish coursePublish = contentServiceClient.getCoursepublish(courseId);
        //获取收费规则
        String charge = coursePublish.getCharge();
        XcChooseCourse xcChooseCourse = null;
        //判断是否免费
        if ("201000".equals(charge)) {
            //免费 加入到选课记录表
            xcChooseCourse = saveChooseCourse(courseId, userId, coursePublish, "701001", "700001");
            //免费 加入到课程表
            saveCourseTable(courseId, userId, xcChooseCourse);
        } else {
            //收费 加入选课记录表
            xcChooseCourse = saveChooseCourse(courseId, userId, coursePublish, "701002", "701002");
        }
        XcChooseCourseDto xcChooseCourseDto = new XcChooseCourseDto();
        BeanUtils.copyProperties(xcChooseCourse, xcChooseCourseDto);
        //获取学习资格
        XcCourseTablesDto xcCourseTablesDto = courseTablesService.getLearnstatus(userId, courseId);
        xcChooseCourseDto.setLearnStatus(xcCourseTablesDto.getLearnStatus());
        //返回
        return xcChooseCourseDto;
    }

    private void saveCourseTable(Long courseId, String userId, XcChooseCourse xcChooseCourse) {
        //查询是否已选择过该课
        LambdaQueryWrapper<XcCourseTables> queryWrapper = new LambdaQueryWrapper<XcCourseTables>()
                .eq(XcCourseTables::getUserId, userId)
                .eq(XcCourseTables::getCourseId, courseId);
        Long count = courseTablesService.getBaseMapper().selectCount(queryWrapper);
        if (count > 0) {
            log.info("userId: {} , 已选择该课: {}", userId, courseId);
            return;
        }
        //获取选课状态
        String status = xcChooseCourse.getStatus();
        if ("701002".equals(status)) {
            //表示待支付
            return;
        }
        XcCourseTables xcCourseTables = new XcCourseTables();
        xcCourseTables.setChooseCourseId(xcChooseCourse.getId());
        xcCourseTables.setCourseId(courseId);
        xcCourseTables.setUserId(userId);
        xcCourseTables.setCompanyId(xcChooseCourse.getCompanyId());
        xcCourseTables.setCourseName(xcChooseCourse.getCourseName());
        xcCourseTables.setCourseType(xcChooseCourse.getOrderType());
        xcCourseTables.setCreateDate(LocalDateTime.now());
        xcCourseTables.setValidTimeStart(xcChooseCourse.getValidTimeStart());
        xcCourseTables.setValidTimeEnd(xcChooseCourse.getValidTimeEnd());
        xcCourseTables.setUpdateDate(LocalDateTime.now());
        courseTablesService.save(xcCourseTables);
    }

    private XcChooseCourse saveChooseCourse(Long courseId, String userId, CoursePublish coursePublish, String status, String orderType) {
        //构造查询条件，根据该条件
        LambdaQueryWrapper<XcChooseCourse> queryWrapper = new LambdaQueryWrapper<XcChooseCourse>()
                .eq(XcChooseCourse::getCourseId, courseId)
                .eq(XcChooseCourse::getUserId, userId)
                .eq(XcChooseCourse::getOrderType, orderType)
                .eq(XcChooseCourse::getStatus, status);
        XcChooseCourse chooseCourse = this.getOne(queryWrapper);
        //若查询不为空，则直接返回，表示已经添加过该课程
        if (chooseCourse != null) {
            return chooseCourse;
        }
        //若查询为空，则添加到选课表
        XcChooseCourse xcChooseCourse = new XcChooseCourse();
        xcChooseCourse.setCourseId(courseId);
        xcChooseCourse.setCourseName(coursePublish.getName());
        xcChooseCourse.setUserId(userId);
        xcChooseCourse.setCompanyId(coursePublish.getCompanyId());
        xcChooseCourse.setCreateDate(LocalDateTime.now());
        xcChooseCourse.setCoursePrice(coursePublish.getPrice());
        xcChooseCourse.setOrderType(orderType);
        xcChooseCourse.setValidDays(coursePublish.getValidDays());
        xcChooseCourse.setStatus(status);
        xcChooseCourse.setValidTimeStart(LocalDateTime.now());
        LocalDate localDate = LocalDate.now().plusDays(coursePublish.getValidDays());
        xcChooseCourse.setValidTimeEnd(LocalDateTime.of(localDate, LocalTime.now()));
        this.save(xcChooseCourse);
        return xcChooseCourse;
    }
}
